package com.chainwintel.prjmgmt.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

import com.chainwintel.prjmgmt.model.User;
import com.chainwintel.prjmgmt.service.UserMgr;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Component
@Results({
	@Result(name = "login-form", location = "login.jsp"),
	@Result(name = "loginFailed", location = "loginFailed.jsp"),
	@Result(name = "welcome",location = "welcome.jsp"),
	@Result(name = "home", location = "home.jsp")
})
public class LoginAction extends ActionSupport implements Preparable {
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -5626721745674977619L;
	private User user;
	
	@Autowired private UserMgr userMgr;

	public void prepare() throws Exception {
		setUser(new User());
	}
	
	@Action("/loginForm")
	public String loginForm() {
		return "login-form";
	}

	@Action("/login")
	public String doLogin() {
		setUser(user);
		if (authenticate()) {
			try {
				User user = userMgr.find(getUser().getId());
				ActionContext.getContext().getSession().put("currentUser", user);
				return "home";
			} catch (DataAccessException e) {
				e.printStackTrace();
				return "loginFailed";
			}
		}
		return "loginFailed";
		
	}
	
	@Action("/logout")
	public String doLogout() {
		if (ActionContext.getContext().getSession().containsKey("currentUser")) {
			ActionContext.getContext().getSession().remove("currentUser");
		}
		return "login-form";
	}
	
	public boolean authenticate() {
		if (getUser() == null || getUser().getUsername() == null || getUser().getUsername().length() < 1 || getUser().getPassword() == null || getUser().getPassword().length() < 1) {
			return false;
		}
		try {
			User	user = userMgr.findByUsernameAndPassword(getUser().getUsername(), getUser().getPassword());
			setUser(user);
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		}
	}

	
	/**
	 * @param user the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

}
